# -*- coding:utf-8 -*-
import requests
from bs4 import BeautifulSoup
from crawl_imu_jwxt.course import Course
from crawl_imu_jwxt.student import Student


class JwxtSpider:

    def __init__(self):
        self.session = requests.session()
        self.login_data = {'zjh': "", 'mm': ""}
        self.login_url = "http://jwxt.imu.edu.cn/loginAction.do"
        self.search_url = "http://jwxt.imu.edu.cn:80/setReportParams"
        self.search_data = {'LS_XH': "", 'resultPage': "http://jwxt.imu.edu.cn:80/reportFiles/cj/cj_zwcjd.jsp?"}
        self.logined = False

    def login(self, zjh, mm):
        """登录保存session"""
        self.login_data['zjh'] = zjh
        self.login_data['mm'] = mm
        login_page = self.session.post(self.login_url, self.login_data)
        login_page_tag = BeautifulSoup(login_page.text, "lxml")
        # 判断是否登录成功
        title = login_page_tag.find("title").string
        if title == u"学分制综合教务":
            # 登录成功
            self.logined = True
            print "Login Success!"
        else:
            print "Login Failed!"

    def get_grade_page1(self, no):
        """获取第一页成绩页面"""
        if not self.logined:
            raise Exception("未登录！")

        self.search_data['LS_XH'] = no
        grade_page1 = self.session.post(self.search_url, self.search_data)
        return grade_page1.text

    def get_grade_page2(self, grade_page1):
        """获取第二页成绩页面(如果没有第二页成绩，会返回一个错误HTML页面)"""
        if not self.logined:
            raise Exception("未登录！")

        page1_tag = BeautifulSoup(grade_page1, "lxml")
        turn_page_form = page1_tag.find(name="form", attrs={"name": "report1_turnPageForm"})
        input_tag_list = turn_page_form.find_all("input")
        form_data = {}
        for input_tag in input_tag_list:
            key = input_tag['name']
            value = input_tag['value']
            form_data[key] = value
        form_data['report1_currPage'] = 2
        form_url = turn_page_form.attrs['action']
        grade_page2 = self.session.post(form_url, form_data)
        return grade_page2.text

    def parse(self, grade_page1, grade_page2):
        page1 = BeautifulSoup(grade_page1, "lxml")
        student = Student()
        # 计数变量
        four_td_num = 0
        eight_td_num = 0
        tr_list = page1.find_all(name="tr", attrs={'height': 20, 'style': 'height:20px;'})
        for tr in tr_list:
            td_list = tr.find_all(name="td")
            length = len(td_list)
            # 姓名相关信息
            if length == 9:
                student.name = td_list[1].string
                student.no = td_list[3].string
                student.gender = td_list[5].string
                student.id = td_list[7].string
            # 籍贯相关信息
            elif length == 8:
                eight_td_num = eight_td_num + 1
                if eight_td_num < 2:
                    student.nation = td_list[1].string
                    student.hometown = td_list[3].string
            # 入学时期
            elif length == 6:
                student.period = td_list[3].string
            # 系、专业
            elif length == 4:
                four_td_num = four_td_num + 1
                if four_td_num == 1:
                    student.major = td_list[1].string
                if four_td_num == 2:
                    student.department = td_list[1].string
            # 成绩
            elif length == 12:
                course_a = Course(td_list[0].string, td_list[1].string, td_list[2].string,
                                  td_list[3].string, td_list[4].string, td_list[5].string)
                student.course_list.append(course_a)
                if td_list[6].string is not None:
                    course_b = Course(td_list[6].string, td_list[7].string, td_list[8].string,
                                      td_list[9].string, td_list[10].string, td_list[11].string)
                    student.course_list.append(course_b)
        # 获取第二个页面的成绩
        page2 = BeautifulSoup(grade_page2, "lxml")
        tr_list = page2.find_all(name="tr", attrs={'height': 20, 'style': 'height:20px;'})
        for tr in tr_list:
            td_list = tr.find_all(name="td")
            if len(td_list) == 12:
                course_a = Course(td_list[0].string, td_list[1].string, td_list[2].string,
                                  td_list[3].string, td_list[4].string, td_list[5].string)
                student.course_list.append(course_a)
                if td_list[6].string is not None:
                    course_b = Course(td_list[6].string, td_list[7].string, td_list[8].string,
                                      td_list[9].string, td_list[10].string, td_list[11].string)
                    student.course_list.append(course_b)

        return student

if __name__ == '__main__':
    spider = JwxtSpider()
    spider.login("0151123920", "0151123920")
    # while True:
    #     no = raw_input("查询的学号:")
    #     page1 = spider.get_grade_page1(no)
    #     page2 = spider.get_grade_page2(page1)
    #     student = spider.parse(page1, page2)
    #     print "姓名：", student.name
    #     print "平均学分绩：", student.calculate_gpa()
    # print student
    # for course in student.course_list:
    #     print course
    # print "总学分：", student.calculate_point()
    search_list = ["0141123419", "0141122230", "0141122061"]
    for search in search_list:
        page1 = spider.get_grade_page1(search)
        page2 = spider.get_grade_page2(page1)
        student = spider.parse(page1, page2)
        print "姓名：", student.name
        print "平均学分绩：", student.calculate_gpa()
